#coding=utf-8
import os
import logging.handlers

from .__local_buffer_handler__ import LocalBufferingHandler
from ..common.__const__ import INI_PATH
from ..utils.ini_config_file import IniConfigFile


class Logger(object):
    """
    本地日志

    :Attributes:
     - log_level: 日志级别，包括debug、info、warn、error四个级别；默认使用debug级别
    """
    def __init__(self, log_level='debug'):
        # 创建handler，用于缓存日志
        self.buffer_handler = LocalBufferingHandler()
        # 创建handler，用于输出控制台日志
        self.control_handler = logging.StreamHandler()
        self.logger = None
        self.levels = {"debug" : logging.DEBUG,
                       "info" : logging.INFO,
                       "warn" : logging.WARN,
                       "error" : logging.ERROR}
        self.log_level = log_level
        self.log_max_byte = 10 * 1024 * 1024
        self.log_backup_count = 10

    def get_logger(self):
        '''记录日志，规范日志格式'''
        if self.logger is not None:
            return self.logger
        self.logger = logging.Logger("Log.Logger")
        # 日志格式化
        logging.Formatter.default_msec_format = '%s.%03d'
        log_control_fmt = logging.Formatter("%(asctime)s [%(levelname)s] -> <%(funcName)s><%(filename)s>:%(message)s")
        log_buffer_fmt = logging.Formatter("%(asctime)s [%(levelname)s] -> <%(funcName)s><%(filename)s>:%(message)s")
        # log_control_fmt = logging.Formatter("%(asctime)s [%(levelname)s] --> %(message)s")
        # log_buffer_fmt = logging.Formatter("[%(levelname)s]%(message)s")
        self.control_handler.setFormatter(log_control_fmt)
        self.buffer_handler.setFormatter(log_buffer_fmt)
        self.logger.addHandler(self.control_handler)
        self.logger.addHandler(self.buffer_handler)
        self.logger.setLevel(self.levels.get(self.log_level))
        return self.logger

    def flush_buffer(self):
        '''清空缓存日志'''
        return self.buffer_handler.close()

    def add_buffer(self,buffer):
        '''添加缓存日志'''
        self.buffer_handler.add_buffer(buffer)


# 创建日志，日志等级从低到高分为：debug,info,warn,error
if os.path.exists(INI_PATH):
    _logger = Logger(IniConfigFile(INI_PATH).read('ReportLevel', 'reportlevel'))
else:
    _logger = Logger()
    _logger.get_logger().warning('执行目录中缺少{}配置文件！'.format(INI_PATH.split('\\')[-1]))

# 日志对象
# Example: logger.info('打印日志。')
logger = _logger.get_logger()